package com.tianji.learning.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 处理课程过期的定时任务
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class LessonStatusCheckTask {
    private final ILearningLessonService iLearningLessonService;

    @Scheduled(cron = "0 * * * * ?")  //秒 分 时 日 月 周 (年)  每分钟执行一次
    public void LessonStatusCheck(){
        LocalDateTime now = LocalDateTime.now();
        // 查询课程表中所有未过期的课程
        LambdaQueryWrapper<LearningLesson> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(LearningLesson::getStatus, LessonStatus.EXPIRED);
        List<LearningLesson> learningLessons = iLearningLessonService.list(lambdaQueryWrapper);
        if (CollUtils.isEmpty(learningLessons)){
            return;
        }
        // 遍历所有未过期的课程，如果遇到当前时间大于过期时间的将状态设置为已过期
        for (LearningLesson learningLesson : learningLessons) {
            if (now.isAfter(learningLesson.getExpireTime())){
                learningLesson.setStatus(LessonStatus.EXPIRED);
            }
        }
        // 批量更新课程状态
        iLearningLessonService.updateBatchById(learningLessons);
    }
}
